<template>
  <basic-container>
    <avue-crud
      :option="option"
      :search.sync="search"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @sort-change="sortChange"
      @row-save="rowSave"
      @on-load="onLoad"
    >
      <template slot="menuLeft">
        <div class="curd-foter">
          <div class="redFontBox">
            扣款金额汇总：<span class="redFont">{{
              exhibition(countData.totalAmount) || 0
            }}</span>
            元
          </div>
        </div>
      </template>
      <template slot="menuRight">
        <el-button type="primary" size="small" @click="setTime('今天')"
          >今天
        </el-button>
        <!-- <el-button type="primary" size="small" @click="setTime('昨天')"
          >昨天
        </el-button> -->
        <el-button type="primary" size="small" @click="setTime('本月')"
          >本月
        </el-button>
        <!-- <el-button
          type="success"
          size="small"
          plain
          icon="el-icon-upload2"
          v-if="permissionList.importBtn"
          @click="handleImport"
          >导入
        </el-button> -->
        <el-button
          type="success"
          size="small"
          plain
          icon="el-icon-upload2"
          @click="handleImport"
          >导入
        </el-button>
        <el-button
          type="warning"
          size="small"
          plain
          icon="el-icon-download"
          v-if="permissionList.exportBtn"
          @click="handleExport"
          >导出
        </el-button>
      </template>
      <template slot-scope="{}" slot="serviceNoSearch">
        <select-page
          ref="searchSerSelect"
          label="serviceName"
          value="serviceNo"
          :select.sync="search.serviceNo"
          :url="website.searchLink.serviceUrl"
          placeholder-text="服务商"
          filter-key="searchParam"
        ></select-page>
      </template>
      <template slot-scope="{}" slot="orgNoSearch">
        <select-page
          ref="searchOrgSelect"
          label="serviceName"
          value="serviceNo"
          :select.sync="search.orgNo"
          :url="website.searchLink.orgUrl"
          placeholder-text="机构"
          filter-key="searchParam"
        ></select-page>
      </template>
      <template slot-scope="{}" slot="rpiNoSearch">
        <select-page
          ref="searchRpiSelect"
          label="rpiName"
          value="rpiNo"
          :select.sync="search.rpiNo"
          :url="website.searchLink.merchantUrl"
          placeholder-text="商户"
          filter-key="searchParam"
        ></select-page>
      </template>
      <template slot-scope="{}" slot="serviceNoForm">
          <select-page
            ref="searchSerSelect"
            label="serviceName"
            value="serviceNo"
            :select.sync="form.serviceNo"
            :url="website.searchLink.serviceUrl"
            placeholder-text="服务商"
            filter-key="searchParam"
          ></select-page>
      </template>
    </avue-crud>
    <el-dialog
      title="数据导入"
      append-to-body
      :visible.sync="excelBox"
      width="555px"
    >
      <avue-form
        :option="excelOption"
        v-model="excelForm"
        :upload-after="uploadAfter"
      >
        <template slot="excelTemplate">
          <el-button type="primary" @click="handleTemplate">
            点击下载<i class="el-icon-download el-icon--right"></i>
          </el-button>
        </template>
      </avue-form>
    </el-dialog>
  </basic-container>
</template>

<script>
import { getList, add, getListCount, getExport, getExportTemplate } from "@/api/rb-oem/active/debt";
import { mapGetters } from "vuex";
import { dateFormat } from "@/util/date";
import { downloadFileExcel } from "@/util/util";
import selectPage from "@/components/select-page/select-page";

export default {
  components: {
    selectPage,
  },
  data() {
    return {
      form: {},
      query: {},
      search: {},
      loading: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      selectionList: [],
      option: {
        height: "calc(50vh - 50px)",
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        viewBtn: true,
        editBtn: false,
        // addBtn: false,
        delBtn: false,
        selection: true,
        searchMenuSpan: 24,
        columnBtn: false,
        labelWidth: 120, //弹出表单的标题的统一宽度
        searchLabelWidth: 120, //搜索框标题宽度
        menuWidth: 100, //操作栏宽度
        emptyBtnText: "重置",
        column: [
          {
            label: "商户类型",
            prop: "rpiTypeName",
            type: "input",
            overHidden: true,
            minWidth: 70,
            searchOrder: 4,
            display: false,
          },
          {
            label: "商户类型",
            prop: "rpiType",
            type: "select",
            search: true,
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            dataType: "number",
            dicUrl: "/api/blade-system/dict/dictionary?code=user_income_type",
            overHidden: true,
            minWidth: 70,
            searchOrder: 4,
            display: false,
            hide: true,
          },
          {
            label: "商户编号",
            searchLabel: "商户",
            prop: "rpiNo",
            type: "select",
            search: true,
            overHidden: true,
            width: 140,
            searchOrder: 4,
            display: false,
          },
          {
            label: "商户注册名称",
            prop: "registeredName",
            type: "input",
            search: true,
            searchOrder: 4,
            width: 200,
            display: false,
          },
          {
            label: "商户简称",
            prop: "userShortName",
            type: "input",
            search: true,
            width: 200,
            searchOrder: 4,
            display: false,
          },
          {
            label: "门头名称",
            prop: "rpiName",
            type: "input",
            width: 200,
            searchOrder: 4,
            display: false,
          },
          {
            label: "服务商编号",
            searchLabel: "服务商",
            prop: "serviceNo",
            type: "select",
            searchOrder: 0,
            search: true,
            span: 24,
            overHidden: true,
            width: 110,
            rules: [
              {
                required: true,
                message: "请选择服务商",
                trigger: "blur",
              },
            ],
          },
          {
            label: "服务商名称",
            prop: "serviceName",
            type: "input",
            searchOrder: 0,
            minWidth: 200,
            display: false,
          },
          {
            label: "",
            prop: "isSelectChild",
            type: "select",
            multiple: false,
            dataType: "string",
            showColumn: false,
            hide: true,
            display: false,
            search: true,
            searchType: "checkbox",
            searchSpan: 0,
            searchLabelWidth: "0",
            searchOrder: 0,
            display: false,
            dicData: [
              {
                label: "包含下级",
                value: 1,
              },
            ],
          },
          {
            label: "机构编号",
            searchLabel: "所属机构",
            prop: "orgNo",
            type: "select",
            searchOrder: 1,
            showColumn: false,
            search: true,
            filterable: true,
            width: 110,
            display: false,
            rules: [
              {
                required: true,
                message: "请选择所属机构",
                trigger: "blur",
              },
            ],
          },
          {
            label: "机构名称",
            prop: "orgName",
            type: "input",
            overHidden: true,
            minWidth: 200,
            display: false,
          },
          {
            label: "活动类型编号",
            prop: "activeCode",
            type: "input",
            overHidden: true,
            width: 120,
            display: false,
          },
          {
            label: "活动类型名称",
            prop: "activeName",
            type: "input",
            overHidden: true,
            minWidth: 140,
            display: false,
          },
          {
            label: "活动开始日期",
            prop: "beginTime",
            type: "input",
            overHidden: true,
            minWidth: 140,
            display: false,
          },
          {
            label: "活动结束日期",
            prop: "endTime",
            type: "input",
            overHidden: true,
            minWidth: 140,
            display: false,
          },
          {
            label: "设备归属",
            prop: "belongToName",
            type: "input",
            ////sortable: true,
            // search: true,
            overHidden: true,
            minWidth: 200,
            // hide: true,
            display: false,
          },
          {
            label: "设备类型",
            prop: "rptName",
            type: "input",
            display: false,
            ////sortable: true,
            // search: true,
            // props: {
            //   label: "dictValue",
            //   value: "dictKey",
            // },
            // dataType: "number",
            // dicUrl: "/api/oem/active/active/selectTypeList",
            // overHidden: true,
            // minWidth:70,
          },
          {
            label: "设备品牌",
            prop: "rpsName",
            type: "input",
            ////sortable: true,
            // search: true,
            overHidden: true,
            minWidth: 200,
            display: false,
            // hide: true,
            // display:false
          },
          {
            label: "设备型号",
            prop: "rpmName",
            type: "input",
            ////sortable: true,
            // search: true,
            overHidden: true,
            minWidth: 200,
            display: false,
            // hide: true,
            // display:false
          },
          {
            label: "设备编号",
            prop: "sn",
            type: "input",
            ////sortable: true,
            // search: true,
            overHidden: true,
            minWidth: 200,
            rules: [
              {
                required: true,
                message: "请填写设备编号",
                trigger: "blur",
              },
            ],
          },
          {
            label: "扣款金额",
            prop: "rewardAmount",
            type: "input",
            ////sortable: true,
            // search: true,
            overHidden: true,
            minWidth: 200,
            rules: [
              {
                required: true,
                message: "请填写扣款金额",
                trigger: "blur",
              },
            ],
          },
          {
            label: "扣款类型",
            prop: "debtType",
            type: "select",
            search: true,
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            dataType: "number",
            dicUrl: "/api/blade-system/dict/dictionary?code=debt_type",
            overHidden: true,
            minWidth: 200,
            rules: [
              {
                required: true,
                message: "请选择扣款类型",
                trigger: "blur",
              },
            ],
          },
          {
            label: "扣款日期",
            prop: "debtTime",
            type: "input",
            ////sortable: true,
            // search: true,
            overHidden: true,
            minWidth: 140,
            display: false,
            // hide: true,
            // display:false
          },
          {
            label: "所属通道",
            prop: "aisleName",
            type: "input",
            ////sortable: true,
            // search: true,
            overHidden: true,
            minWidth: 110,
            display: false,
            // hide: true,
            // display:false
          },
          {
            label: "扣款日期",
            prop: "timeData",
            type: "datetimerange",
            searchRange: true,
            defaultTime: ["00:00:00", "23:59:59"],
            format: "yyyy-MM-dd HH:mm:ss",
            valueFormat: "yyyy-MM-dd HH:mm:ss",
            startPlaceholder: "扣款日期开始时间",
            endPlaceholder: "扣款日期结束时间",
            search: true,
            display: false,
            rules: [
              {
                required: true,
                message: "请选择扣款日期",
                trigger: "blur",
              },
            ],
            hide: true,
            display: false,
            searchSpan: 12,
          },
          {
            label: "扣款备注",
            prop: "remark",
            type: "textarea",
            overHidden: true,
            minWidth: 140,
          },
        ],
      },
      data: [],
      excelBox: false,
      excelForm: {},
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: "模板上传",
            prop: "excelFile",
            type: "upload",
            drag: true,
            loadText: "模板上传中，请稍等",
            span: 24,
            propsHttp: {
              res: "data",
            },
            tip: "请上传 .xls,.xlsx 标准格式文件",
            action: "/api/rb-oem/oem/active/activerecord/importDebt",
          },
          {
            label: "模板下载",
            prop: "excelTemplate",
            formslot: true,
            span: 24,
          },
        ],
      },
      countData: {},
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        // addBtn: this.vaildData(this.permission.trade_add, false),
        viewBtn: this.vaildData(this.permission.active_debt_view, false),
        // delBtn: this.vaildData(this.permission.trade_delete, false),
        // editBtn: this.vaildData(this.permission.trade_edit, false),
        exportBtn: this.vaildData(this.permission.active_debt_export, false),
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
    // 交易状态
    rptPayStateType() {
      return (row) => {
        if (row.rptPayState == 0) {
          return "#E6A23C"; //未支付
        } else if (row.rptPayState == 1 && row.rptIsRefund !== 0) {
          return "#6463bf"; //支付成功（已退款）
        } else if (row.rptPayState == 1) {
          return "#67C23A"; //支付成功
        } else if (row.rptPayState == 2) {
          return "#909399"; //支付失败
        } else if (row.rptPayState == 3) {
          return "#909399"; //取消支付
        } else if (row.rptPayState == 4) {
          return "#909399"; //退款中
        } else if (row.rptPayState == 5) {
          return "#2fdeebf2"; //已退款
        } else if (row.rptPayState == 6) {
          return "#909399"; //退款失败
        } else {
          return "#909399";
        }
      };
    },
    exhibition() {
      return (val) => {
        if (val == "" || val == "-1") {
          return (val = 0);
        } else {
          return val;
        }
      };
    },
  },
  watch: {
    "search.timeData"(val) {
      if (val) {
        this.search.beginTime = val[0];
        this.search.endTime = val[1];
      } else {
        this.search.beginTime = "";
        this.search.endTime = "";
      }
    },
  },
  created() {
    // this.getServiceInfoSimpleList({isSelectChild:0})
  },
  methods: {
    /**
     * @func 设置时间
     * @desc 点击获取点击天数时间
     * @param {Object} type - 今天，昨天，近七天
     * */
    setTime(type) {
      let date = new Date();
      this.query = {};
      if (type == "今天") {
        this.search.beginTime = dateFormat(date, "yyyy-MM-dd") + " 00:00:00";
        this.search.endTime = dateFormat(date, "yyyy-MM-dd") + " 23:59:59";
        this.search.timeData = [this.search.beginTime, this.search.endTime];
        this.page.currentPage = 1;
        this.forInSearch();
        this.refreshChange();
      } else if (type == "昨天") {
        this.search.beginTime =
          dateFormat(
            new Date(date.getTime() - 3600 * 1000 * 24 * 1),
            "yyyy-MM-dd"
          ) + " 00:00:00";
        this.search.endTime =
          dateFormat(
            new Date(date.getTime() - 3600 * 1000 * 24 * 1),
            "yyyy-MM-dd"
          ) + " 23:59:59";
        this.search.timeData = [this.search.beginTime, this.search.endTime];
        this.page.currentPage = 1;
        this.forInSearch();
        this.refreshChange();
      } else {
        // "本月"
        this.search.beginTime = dateFormat(date, "yyyy-MM") + "-01 00:00:00";
        this.search.endTime = dateFormat(date, "yyyy-MM-dd") + " 23:59:59";
        this.search.timeData = [this.search.beginTime, this.search.endTime];
        this.page.currentPage = 1;
        this.forInSearch();
        this.refreshChange();
      }
    },
    forInSearch() {
      for (let key in this.search) {
        if (this.search[key]) {
          if (key.indexOf("$") == -1) {
            this.query[key] = this.search[key];
          }
        }
      }
    },
    /**
     * @func edit,view 打开之前回调
     * @desc 点击获取点击天数时间
     * */
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        // getDetail(this.form.id).then(res => {
        //   this.form = res.data.data;
        // });
      }
      done();
    },
    /**
     * @func 重置
     * @desc 重置查询条件
     * */
    searchReset() {
      this.query = {};
      this.search = {};
      this.$set(this.search, "timeData", ["", ""]);
      this.onLoad(this.page);
    },
    /**
     * @func 搜索
     * @desc 根据条件查询
     * @param {params} params --- 条件查询
     * */
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    /**
     * @func 选中单元格
     * @desc 选中单元格数据
     * @param {list} list --- 选中单元格数据-数组
     * */
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    /**
     * @func 分页页码
     * @desc 分页页码改变时会触发
     * */
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      // this.refreshChange();
    },
    /**
     * @func 当前页个数
     * @desc pageSize改变时会触发
     * */
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      // this.refreshChange();
    },
    /**
     * @func 刷新
     * @desc 点击刷新按钮触发该事件
     * */
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    rowSave(row, done, loading) {
      add(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        loading();
        window.console.log(error);
      });
    },
    /**
     * @func 初始化
     * @desc 表格初始化查询数据
     * */
    onLoad(page, params = {}) {
      this.loading = true;
      // if(this.query.isSelectChildArr){
      //   this.query.isSelectChild = this.query.isSelectChildArr[0];
      // }
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query)
      ).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });

      /**
       * @func 统计
       * @desc 根据条件获取统计
       * */
      getListCount(Object.assign(params, this.query)).then((res) => {
        this.countData = res.data.data;
      });
    },
    handleImport() {
      this.excelBox = true;
    },
    /**
     * @func 导出
     * @desc 根据条件导出
     * */
    handleExport() {
      if (this.search.timeData[0]) {
        this.search.beginTime = this.search.timeData[0];
      }
      if (this.search.timeData[1]) {
        this.search.endTime = this.search.timeData[1];
      }

      let params = {
        ...this.search,
        current: "-1",
        size: "-1",
      };

      this.$confirm("是否导出用户数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        getExport(this.query).then((res) => {
            // downloadFileExcel(res);
            this.$message({
              type: "success",
              message: res.data.msg
            });
          },
          (error) => {
            window.console.log(error);
          }
        );
      });
    },

    /**
     * @func 排序
     * @desc 根据表格字段排序
     * */
    sortChange(val) {
      if (val.order == "ascending") {
        //正序
        this.query.ascs = val.prop;
        this.query.descs = "";
      } else {
        //倒序
        this.query.descs = val.prop;
        this.query.ascs = "";
      }
      this.refreshChange();
    },
    uploadAfter(res, done) {
      this.excelBox = false;
      this.refreshChange();
      done();
    },
    handleTemplate() {
      getExportTemplate().then((res) => {
          downloadFileExcel(res);
        },
        (error) => {
          window.console.log(error);
        }
      );
    },
  },
};
</script>

<style lang="scss" scoped>
.curd-foter {
  padding-top: 10px;
  display: flex;
  flex-wrap: wrap;
}

.redFontBox {
  margin-right: 40px;
  .redFont {
    color: red;
  }
}
/deep/ .el-tag--dark.el-tag--success {
  border: none !important;
}
</style>
